package com.yourname.bank_sim.menu;

import com.yourname.bank_sim.DataStore;
import com.yourname.bank_sim.entity.Account;
import com.yourname.bank_sim.entity.ActionLog;

import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

/**
 * 菜单类，此项目的菜单结构比较简单，所以就用这一个类即可
 */
public class Menu {
    private static Scanner scanner=new Scanner(System.in);
    private static Account account;//获取已经登陆的账户信息
    private static void record(Account account,BigDecimal amount,String actionType,boolean isOk){
        ActionLog log=new ActionLog();
        log.setActor(account.getAccountNumber());
        log.setActionType(actionType);
        log.setAmount(amount);
        log.setBalence(account.getBalence());
        log.setDate(new Date());
        log.setSuccess(isOk);
        DataStore.addActionLog(log);
        DataStore.saveData();
    }
    private static void actions() {
        while (true){
            System.out.println("""
                1. 查询余额
                2. 存款
                3. 取款
                4. 转账
                5. 查阅记录
                6. 返回上一级
                """);
            int i = scanner.nextInt();
            if (i==6){
                break;
            }
            switch (i){
                case 1->{

                    System.out.printf("""
                        账户：%s
                        余额：%.2f
                        """,account.getAccountNumber(),account.getBalence());
                }
                case 2->{
                    System.out.println("请输入存入的金额（最多两位小数）");
                    BigDecimal in = scanner.nextBigDecimal();
                    in=in.setScale(2,RoundingMode.FLOOR);//超出两位小数后下取整处理
                    BigDecimal balence = account.getBalence();
                    balence=balence.add(in);
                    account.setBalence(balence);
                    record(account,in,"存款",true);
                    DataStore.updateAccount(account);
                    DataStore.saveData();
                }
                case 3->{
                    System.out.println("请输入取出金额");
                    BigDecimal out = scanner.nextBigDecimal();
                    out=out.setScale(2,RoundingMode.FLOOR);
                    BigDecimal balence = account.getBalence();
                    if (balence.compareTo(out)>=0){
                        account.setBalence(balence.subtract(out));
                        record(account,out,"取出",true);
                        DataStore.updateAccount(account);
                        DataStore.saveData();
                    }else{
                        record(account,out,"取出",false);
                        System.out.println("余额不足。");
                    }
                }
                case 4->{
                    System.out.println("请输入转账目标的账号：");
                    String target = scanner.next();
                    Account accountByAccountNumber = DataStore.getAccountByAccountNumber(target);
                    if (accountByAccountNumber==null){
                        System.out.println("没有这个账号！");
                        record(account,new BigDecimal("0.00"),"转账",false);
                    }else {
                        System.out.println("请输入取出金额：");
                        BigDecimal out = scanner.nextBigDecimal();
                        out=out.setScale(2,RoundingMode.FLOOR);
                        BigDecimal balence = account.getBalence();
                        if (balence.compareTo(out)>=0){
                            account.setBalence(balence.subtract(out));
                            BigDecimal remain = accountByAccountNumber.getBalence();
                            accountByAccountNumber.setBalence(remain.add(out));
                            DataStore.updateAccount(account);
                            DataStore.updateAccount(accountByAccountNumber);
                            record(account,out,"转出",true);
                            record(accountByAccountNumber,out,"转入",true);
                        }else{
                            System.out.println("余额不足。");
                            record(account,out,"转出",false);
                        }
                    }
                }
                case 5->{
                    String fileName="actionlog_"+account.getAccountNumber()+".csv";
                    File f=new File(fileName);
                    String date_format="YYYY-MM-dd HH:mm:ss";

                    try {
                        BufferedWriter bw=new BufferedWriter(new FileWriter(f));
                        List<ActionLog> logs = DataStore.getLogsByAccountNumber(account.getAccountNumber());
                        bw.write("序号,操作日期,操作账号,操作金额,余额,操作类型,状态\n");
                        SimpleDateFormat dateFormat=new SimpleDateFormat(date_format);
                        for (int j=1;j<=logs.size();j++){
                            ActionLog log = logs.get(j - 1);
                            String format = dateFormat.format(log.getDate());
                            String log_str = String.format("%d,%s,%s,%.2f,%.2f,%s,%s\n", j,format, log.getActor(), log.getAmount()
                                    , log.getBalence(), log.getActionType(), log.isSuccess() ? "成功" : "失败");
                            bw.write(log_str);
                        }
                        bw.close();
                        System.out.println("已成功将日志文件保存至"+fileName+"中");
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }

    }
    private static void loginAction(){
        System.out.println("请输入账号和密码，中间用短横-分割");
        String next = scanner.next();
        String[] split = next.split("-");
        Account account = DataStore.getAccountByAccountAndPassword(split[0], split[1]);
        if (account!=null){
            Menu.account=account;
            actions();
        }else{
            System.out.println("登陆失败");
        }
    }
    private static void registAction(){
        System.out.println("请输入账号和密码，中间用短横-分割");
        String next = scanner.next();
        String[] split = next.split("-");
        Account account=new Account();
        account.setAccountNumber(split[0]);
        account.setPassword(split[1]);
        account.setBalence(new BigDecimal("0.00").setScale(2, RoundingMode.FLOOR));
        DataStore.addAccount(account);
        DataStore.saveData();
        System.out.println("添加成功");
    }
    public static void menu(){
        while (true){
            System.out.println("""
                1. 登录
                2. 注册
                3. 退出
                """);
            int i = scanner.nextInt();
            if (i==3){
                break;
            }
            switch (i){
                case 1->loginAction();
                case 2->registAction();
            }
        }

    }
}
